<template>
  <div class="dict-management">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 字典类型 -->
      <el-tab-pane label="字典类型" name="type">
        <!-- 搜索栏 -->
        <el-card class="search-card">
          <el-form :model="typeSearchForm" ref="typeSearchFormRef" inline>
            <el-form-item label="字典名称" prop="dictName">
              <el-input
                v-model="typeSearchForm.dictName"
                placeholder="请输入字典名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="字典类型" prop="dictType">
              <el-input
                v-model="typeSearchForm.dictType"
                placeholder="请输入字典类型"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="typeSearchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleTypeSearch">查询</el-button>
              <el-button @click="handleTypeReset">重置</el-button>
              <el-button type="success" @click="handleTypeAdd">新增字典</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 字典类型表格 -->
        <el-card class="table-card">
          <el-table
            :data="typeTableData"
            style="width: 100%"
            v-loading="typeLoading"
            border
            stripe
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="dictName" label="字典名称" width="150" />
            <el-table-column prop="dictType" label="字典类型" width="150" />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
                  {{ scope.row.status === '1' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleViewData(scope.row)"
                >
                  字典数据
                </el-button>
                <el-button
                  link
                  type="primary"
                  @click="handleTypeEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleTypeDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="typeCurrentPage"
              v-model:page-size="typePageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="typeTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleTypeSizeChange"
              @current-change="handleTypeCurrentChange"
            />
          </div>
        </el-card>

        <!-- 字典类型表单弹窗 -->
        <el-dialog
          v-model="typeDialogVisible"
          :title="typeFormType === 'add' ? '新增字典类型' : '编辑字典类型'"
          width="600px"
          destroy-on-close
        >
          <el-form
            ref="typeFormRef"
            :model="typeForm"
            :rules="typeRules"
            label-width="100px"
          >
            <el-form-item label="字典名称" prop="dictName">
              <el-input
                v-model="typeForm.dictName"
                placeholder="请输入字典名称"
              />
            </el-form-item>
            <el-form-item label="字典类型" prop="dictType">
              <el-input
                v-model="typeForm.dictType"
                placeholder="请输入字典类型"
                :disabled="typeFormType === 'edit'"
              />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="typeForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入描述"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="typeForm.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="typeDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleTypeSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- 字典数据 -->
      <el-tab-pane label="字典数据" name="data" v-if="showDataTab">
        <div class="dict-data-header">
          <el-page-header @back="handleBack" :title="currentDictType?.dictName" />
        </div>
        
        <!-- 搜索栏 -->
        <el-card class="search-card">
          <el-form :model="dataSearchForm" ref="dataSearchFormRef" inline>
            <el-form-item label="字典标签" prop="dictLabel">
              <el-input
                v-model="dataSearchForm.dictLabel"
                placeholder="请输入字典标签"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="dataSearchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleDataSearch">查询</el-button>
              <el-button @click="handleDataReset">重置</el-button>
              <el-button type="success" @click="handleDataAdd">新增字典数据</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 字典数据表格 -->
        <el-card class="table-card">
          <el-table
            :data="dataTableData"
            style="width: 100%"
            v-loading="dataLoading"
            border
            stripe
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="dictLabel" label="字典标签" width="150" />
            <el-table-column prop="dictValue" label="字典键值" width="150" />
            <el-table-column prop="dictSort" label="排序" width="80" />
            <el-table-column prop="cssClass" label="样式属性" width="120" />
            <el-table-column prop="listClass" label="回显样式" width="120">
              <template #default="scope">
                <el-tag
                  v-if="scope.row.listClass"
                  :type="scope.row.listClass"
                >
                  {{ scope.row.dictLabel }}
                </el-tag>
                <span v-else>{{ scope.row.dictLabel }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isDefault" label="是否默认" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.isDefault === 'Y' ? 'success' : 'info'">
                  {{ scope.row.isDefault === 'Y' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
                  {{ scope.row.status === '1' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleDataEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDataDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="dataCurrentPage"
              v-model:page-size="dataPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="dataTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleDataSizeChange"
              @current-change="handleDataCurrentChange"
            />
          </div>
        </el-card>

        <!-- 字典数据表单弹窗 -->
        <el-dialog
          v-model="dataDialogVisible"
          :title="dataFormType === 'add' ? '新增字典数据' : '编辑字典数据'"
          width="600px"
          destroy-on-close
        >
          <el-form
            ref="dataFormRef"
            :model="dataForm"
            :rules="dataRules"
            label-width="100px"
          >
            <el-form-item label="字典类型">
              <el-input v-model="currentDictType.dictType" disabled />
            </el-form-item>
            <el-form-item label="字典标签" prop="dictLabel">
              <el-input
                v-model="dataForm.dictLabel"
                placeholder="请输入字典标签"
              />
            </el-form-item>
            <el-form-item label="字典键值" prop="dictValue">
              <el-input
                v-model="dataForm.dictValue"
                placeholder="请输入字典键值"
              />
            </el-form-item>
            <el-form-item label="排序" prop="dictSort">
              <el-input-number v-model="dataForm.dictSort" :min="0" :max="999" />
            </el-form-item>
            <el-form-item label="样式属性" prop="cssClass">
              <el-input
                v-model="dataForm.cssClass"
                placeholder="请输入样式属性"
              />
            </el-form-item>
            <el-form-item label="回显样式" prop="listClass">
              <el-select v-model="dataForm.listClass" placeholder="请选择回显样式" style="width: 100%">
                <el-option label="默认" value="" />
                <el-option label="主要" value="primary" />
                <el-option label="成功" value="success" />
                <el-option label="信息" value="info" />
                <el-option label="警告" value="warning" />
                <el-option label="危险" value="danger" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否默认" prop="isDefault">
              <el-radio-group v-model="dataForm.isDefault">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="dataForm.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="dataForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dataDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleDataSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictApi } from '@/api/system'

// 当前激活的标签页
const activeTab = ref('type')
const showDataTab = ref(false)
const currentDictType = ref({})

// 字典类型相关
const typeSearchForm = reactive({
  dictName: '',
  dictType: '',
  status: ''
})

const typeLoading = ref(false)
const typeCurrentPage = ref(1)
const typePageSize = ref(10)
const typeTotal = ref(0)
const typeTableData = ref([])

const typeDialogVisible = ref(false)
const typeFormType = ref('add')
const typeFormRef = ref(null)
const typeForm = reactive({
  id: '',
  dictName: '',
  dictType: '',
  description: '',
  status: '1'
})

const typeRules = {
  dictName: [
    { required: true, message: '请输入字典名称', trigger: 'blur' }
  ],
  dictType: [
    { required: true, message: '请输入字典类型', trigger: 'blur' }
  ]
}

// 字典数据相关
const dataSearchForm = reactive({
  dictLabel: '',
  status: ''
})

const dataLoading = ref(false)
const dataCurrentPage = ref(1)
const dataPageSize = ref(10)
const dataTotal = ref(0)
const dataTableData = ref([])

const dataDialogVisible = ref(false)
const dataFormType = ref('add')
const dataFormRef = ref(null)
const dataForm = reactive({
  id: '',
  dictLabel: '',
  dictValue: '',
  dictSort: 0,
  cssClass: '',
  listClass: '',
  isDefault: 'N',
  status: '1',
  remark: ''
})

const dataRules = {
  dictLabel: [
    { required: true, message: '请输入字典标签', trigger: 'blur' }
  ],
  dictValue: [
    { required: true, message: '请输入字典键值', trigger: 'blur' }
  ],
  dictSort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 字典类型方法
const handleTypeSearch = async () => {
  typeLoading.value = true
  try {
    const params = {
      pageNum: typeCurrentPage.value,
      pageSize: typePageSize.value,
      dictName: typeSearchForm.dictName,
      dictType: typeSearchForm.dictType,
      status: typeSearchForm.status
    }
    
    const res = await dictApi.getTypeList(params)
    if (res.data) {
      typeTableData.value = res.data.list || []
      typeTotal.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取字典类型列表失败', error)
    ElMessage.error('获取字典类型列表失败')
  } finally {
    typeLoading.value = false
  }
}

const handleTypeReset = () => {
  typeSearchForm.dictName = ''
  typeSearchForm.dictType = ''
  typeSearchForm.status = ''
  typeCurrentPage.value = 1
  handleTypeSearch()
}

const handleTypeSizeChange = (val) => {
  typePageSize.value = val
  handleTypeSearch()
}

const handleTypeCurrentChange = (val) => {
  typeCurrentPage.value = val
  handleTypeSearch()
}

const handleTypeAdd = () => {
  typeFormType.value = 'add'
  typeForm.id = ''
  typeForm.dictName = ''
  typeForm.dictType = ''
  typeForm.description = ''
  typeForm.status = '1'
  typeDialogVisible.value = true
}

const handleTypeEdit = (row) => {
  typeFormType.value = 'edit'
  typeForm.id = row.id
  typeForm.dictName = row.dictName
  typeForm.dictType = row.dictType
  typeForm.description = row.description
  typeForm.status = row.status
  typeDialogVisible.value = true
}

const handleTypeDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除字典类型 ${row.dictName} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await dictApi.deleteType(row.id)
      ElMessage.success('删除成功')
      handleTypeSearch()
    } catch (error) {
      console.error('删除字典类型失败', error)
      ElMessage.error('删除字典类型失败')
    }
  }).catch(() => {})
}

const handleTypeSubmit = async () => {
  typeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (typeFormType.value === 'add') {
          await dictApi.addType(typeForm)
          ElMessage.success('添加成功')
        } else {
          await dictApi.updateType(typeForm)
          ElMessage.success('修改成功')
        }
        typeDialogVisible.value = false
        handleTypeSearch()
      } catch (error) {
        console.error('提交字典类型数据失败', error)
        ElMessage.error('提交字典类型数据失败')
      }
    }
  })
}

// 字典数据方法
const handleViewData = (row) => {
  currentDictType.value = row
  showDataTab.value = true
  activeTab.value = 'data'
  dataCurrentPage.value = 1
  dataPageSize.value = 10
  handleDataSearch()
}

const handleBack = () => {
  activeTab.value = 'type'
  showDataTab.value = false
}

const handleDataSearch = async () => {
  if (!currentDictType.value.dictType) return
  
  dataLoading.value = true
  try {
    const params = {
      pageNum: dataCurrentPage.value,
      pageSize: dataPageSize.value,
      dictType: currentDictType.value.dictType,
      dictLabel: dataSearchForm.dictLabel,
      status: dataSearchForm.status
    }
    
    const res = await dictApi.getDataList(params)
    if (res.data) {
      dataTableData.value = res.data.list || []
      dataTotal.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取字典数据列表失败', error)
    ElMessage.error('获取字典数据列表失败')
  } finally {
    dataLoading.value = false
  }
}

const handleDataReset = () => {
  dataSearchForm.dictLabel = ''
  dataSearchForm.status = ''
  dataCurrentPage.value = 1
  handleDataSearch()
}

const handleDataSizeChange = (val) => {
  dataPageSize.value = val
  handleDataSearch()
}

const handleDataCurrentChange = (val) => {
  dataCurrentPage.value = val
  handleDataSearch()
}

const handleDataAdd = () => {
  dataFormType.value = 'add'
  dataForm.id = ''
  dataForm.dictLabel = ''
  dataForm.dictValue = ''
  dataForm.dictSort = 0
  dataForm.cssClass = ''
  dataForm.listClass = ''
  dataForm.isDefault = 'N'
  dataForm.status = '1'
  dataForm.remark = ''
  dataDialogVisible.value = true
}

const handleDataEdit = (row) => {
  dataFormType.value = 'edit'
  dataForm.id = row.id
  dataForm.dictLabel = row.dictLabel
  dataForm.dictValue = row.dictValue
  dataForm.dictSort = row.dictSort
  dataForm.cssClass = row.cssClass
  dataForm.listClass = row.listClass
  dataForm.isDefault = row.isDefault
  dataForm.status = row.status
  dataForm.remark = row.remark
  dataDialogVisible.value = true
}

const handleDataDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除字典数据 ${row.dictLabel} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await dictApi.deleteData(row.id)
      ElMessage.success('删除成功')
      handleDataSearch()
    } catch (error) {
      console.error('删除字典数据失败', error)
      ElMessage.error('删除字典数据失败')
    }
  }).catch(() => {})
}

const handleDataSubmit = async () => {
  dataFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...dataForm,
          dictType: currentDictType.value.dictType
        }
        
        if (dataFormType.value === 'add') {
          await dictApi.addData(data)
          ElMessage.success('添加成功')
        } else {
          await dictApi.updateData(data)
          ElMessage.success('修改成功')
        }
        dataDialogVisible.value = false
        handleDataSearch()
      } catch (error) {
        console.error('提交字典数据失败', error)
        ElMessage.error('提交字典数据失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  handleTypeSearch()
})
</script>

<style scoped>
.dict-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dict-data-header {
  margin-bottom: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 